//
//  WaterflowLayout.m
//  WaterFlowPractice
//
//  Created by mac on 16-5-17.
//  Copyright (c) 2016年 mac. All rights reserved.
//

#import "WaterflowLayout.h"

@implementation WaterflowLayout

#pragma mark -懒加载
- (NSMutableArray *)columsMaxY
{
    if (!_columsMaxY) {
        _columsMaxY = [[NSMutableArray alloc] init];
    }
    
    return _columsMaxY;
}

- (NSMutableArray *)attrsArray
{
    if (!_attrsArray) {
        _attrsArray = [[NSMutableArray alloc] init];
    }
    return _attrsArray;
}

#pragma mark -具体实现

#pragma mark -返回collocationView的contentSize
- (CGSize)collectionViewContentSize
{
    __block CGFloat tempMaxY = [_columsMaxY[0] doubleValue];
    
    [_columsMaxY enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
       
        if (tempMaxY < [obj doubleValue]) {
            tempMaxY = [obj doubleValue];
        }
        
    }];
    return CGSizeMake(ColloctionView_WIDTH, tempMaxY + DefaultEdgeInsets.bottom);
//或
//    return CGSizeMake(0, tempMaxY + DefaultEdgeInsets.bottom);
}


- (void)prepareLayout
{
    
    [super prepareLayout];
    
    [self.columsMaxY removeAllObjects];
    
    for (int i = 0; i < DefaultColumsCount ; i ++) {
        [_columsMaxY addObject:@(DefaultEdgeInsets.top)];
    }
    
    [self.attrsArray removeAllObjects];
    
    NSInteger countInSection = [self.collectionView numberOfItemsInSection:0];
    for (int i = 0; i < countInSection;  i ++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        
        UICollectionViewLayoutAttributes *attrs = [self layoutAttributesForItemAtIndexPath:indexPath];
        [_attrsArray addObject:attrs];
    }
    
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    
    CGFloat xMarginCount = DefaultEdgeInsets.left + DefaultEdgeInsets.right + DefaultRowMargin * (DefaultColumsCount - 1);
    CGFloat cellWidth = (ColloctionView_WIDTH - xMarginCount)/DefaultColumsCount;
    CGFloat cellHeight = [self.delegate getCellHeightAtIndexPath:indexPath] + cellWidth/1.3;
    
    __block CGFloat tempMinY = [_columsMaxY[0] doubleValue];
    __block NSInteger minXIndex = 0;
    
    [_columsMaxY enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if (tempMinY > [obj doubleValue]) {
            tempMinY = [obj doubleValue];
            minXIndex = idx;
        }
    }];
    
    CGFloat cellX = DefaultEdgeInsets.left + minXIndex * (cellWidth + DefaultColumnMargin);
    
    CGFloat cellY = tempMinY + DefaultRowMargin;
    
    attrs.frame = CGRectMake(cellX, cellY, cellWidth, cellHeight);
    
    _columsMaxY[minXIndex] = @(CGRectGetMaxY(attrs.frame));
    
    return attrs;
}


//告诉collectionView每个cell以什么样的样式展示
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    return _attrsArray;
}


@end
















